package com.sip.stream.utils.zfy.proxy;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import androidx.core.os.EnvironmentCompat;

import com.blankj.utilcode.util.SPUtils;
import com.google.gson.JsonObject;
import com.sip.stream.ClientApp;
import com.sip.stream.helper.ZFYPlatformSettingHelper;
import com.sip.stream.rxbus.RxBus;
import com.sip.stream.utils.zfy.RxBusTag;
import com.sip.stream.utils.zfy.ZFYLocation;
import com.sip.stream.utils.zfy.ZFYPlatform;
import com.sip.stream.utils.zfy.config.IPlatformMediaConfig;
import com.sip.stream.utils.zfy.consumer.IGSPlatformConsumer;
import com.sip.stream.utils.zfy.encoder.IGSVideoEncoder;
import com.sip.stream.utils.zfy.event.ZFYPlatformEvent;
import com.sip.stream.utils.zfy.handler.IZFYPlatformHandler;
import com.sip.stream.utils.zfy.status.ZFYStatus;

import java.lang.ref.WeakReference;

import io.reactivex.Single;

public class PlatformProxy{
    private static final String TAG = "PlatformProxy";

    private static final String SAVE_PLATFORM_KEY = "SAVE_PLATFORM_KEY";

    private static PlatformProxy shareInstance;
    private WeakReference<Application> applicationWeakReference;
    private IPlatformMediaConfig cachePlatformMediaConfig;
    private IZFYPlatformHandler handler;
    private PlatformKeepaliveTask keepaliveTask;
    private String platformKey = ZFYPlatform.GB28181;

    public String getPlatformKey() {
        return this.platformKey;
    }

    public void setPlatformKey(String platformKey) {
        this.platformKey = platformKey;
        SPUtils.getInstance().put(SAVE_PLATFORM_KEY,platformKey);
    }

    public static PlatformProxy getInstance() {
        if (shareInstance == null) {
            synchronized (PlatformProxy.class) {
                shareInstance = new PlatformProxy();
                shareInstance.platformKey =SPUtils.getInstance().getString(SAVE_PLATFORM_KEY,"GB28181");
            }
        }
        return shareInstance;
    }

    public boolean registerHandler(String handler) {
        Log.i(TAG, "registerHandler");
        try {
            Object newInstance = Class.forName(handler).newInstance();
            if (newInstance instanceof IZFYPlatformHandler) {
                this.handler = (IZFYPlatformHandler) newInstance;
                return true;
            }
            Log.e(TAG, "object not instanceof IZFYPlatformHandler" + handler);
            return false;
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
            Log.w(TAG, e.getLocalizedMessage());
            return false;
        }
    }

    public void registerPlatform(Context context) {
        Log.i(TAG, "registerPlatform");
        if (this.handler == null)
        {
            String platformHandlerClassPath = ZFYPlatformSettingHelper.getPlatformHandlerClassPath(this.platformKey);
            if (platformHandlerClassPath == null) {
                return;
            }
            registerHandler(platformHandlerClassPath);
        }
        if (this.handler != null) {
            this.handler.registerPlatform(context);
            RxBus.getDefault().subscribe(this, RxBusTag.PLATFORMEVENT, new RxBus.Callback<ZFYPlatformEvent>() {
                @Override
                public void onEvent(ZFYPlatformEvent zFYPlatformEvent) {
                    RxBus.getDefault().post("connect", RxBusTag.PLATFORM_CONTECT);
                    String type = zFYPlatformEvent.getType();
                    type.hashCode();
                    if (type.equals(ZFYPlatformEvent.EVENT_TYPE_REGUSTER_SUCCESS)) {
                        PlatformProxy.this.stopKeepAlive();
                    } else if (type.equals(ZFYPlatformEvent.EVENT_TYPE_REGUSTER_KEEP_ALIVE)) {
                        PlatformProxy.this.startKeepAlive();
                    }
                }
            });
        }
    }

    public void unregisterPlatform() {
        RxBus.getDefault().post("disconnect", RxBusTag.PLATFORM_CONTECT);
        if (this.handler != null) {
            this.handler.unregisterPlatform();
        }
        Log.i(TAG, "RxBus unregister");
        RxBus.getDefault().unregister(this);
        startKeepAlive();
    }

    public void stopStreaming() {
        if (this.handler != null) {
            this.handler.stopStreaming();
        }
    }

    public void stopVideoStreaming() {
        if (this.handler != null) {
            this.handler.stopVideoStreaming();
        }
    }

    public IGSPlatformConsumer createPlatformConsumer(IGSVideoEncoder iGSVideoEncoder) {
        if (this.handler != null) {
            return this.handler.createPlatformConsumer(iGSVideoEncoder);
        }
        return null;
    }


    public void syncPlatformMediaConfig(IPlatformMediaConfig iPlatformMediaConfig) {
        this.cachePlatformMediaConfig = iPlatformMediaConfig;
        if (this.handler != null) {
            this.handler.syncPlatformMediaConfig(iPlatformMediaConfig);
        }
    }

    public void setupApplication(Application application) {
        this.applicationWeakReference = new WeakReference<>(application);
        if (this.handler == null) {
            String platformHandlerClassPath = ZFYPlatformSettingHelper.getPlatformHandlerClassPath(this.platformKey);
            if (platformHandlerClassPath == null) {
                return;
            }
            registerHandler(platformHandlerClassPath);
        }
        if (this.handler != null) {
            this.handler.setupApplication(application);
        }
    }

    private Application getApplication() {
        WeakReference<Application> weakReference = this.applicationWeakReference;
        if (weakReference != null) {
            return weakReference.get();
        }
        return null;
    }


    public void startKeepAlive() {
        if (this.handler != null && this.keepaliveTask == null) {
            PlatformKeepaliveTask platformKeepaliveTask = new PlatformKeepaliveTask(ClientApp.clientApp, new PlatformKeepaliveTask.PlatformKeepaliveListener() {
                @Override
                public void onKeeyAlive() {
                    if (PlatformProxy.this.handler != null) {
                        PlatformProxy.this.handler.registerPlatform(ClientApp.clientApp);
                    }
                }
            });
            this.keepaliveTask = platformKeepaliveTask;
            platformKeepaliveTask.nextKeepalive();
        }
    }

    public void stopKeepAlive() {
        if (this.keepaliveTask != null) {
            this.keepaliveTask.stopKeepalive();
            this.keepaliveTask = null;
        }
    }

    public Intent getGroupintercomIntent(Context context) {
        if (this.handler != null) {
            return this.handler.getGroupintercomIntent(context);
        }
        return null;
    }

    public void updateLocation(ZFYLocation zFYLocation) {
        if (this.handler != null) {
            this.handler.updateLocation(zFYLocation);
        }
    }

    public void updateStatus() {
        if (this.handler != null) {
            this.handler.updateStatus(ZFYStatus.getInstance());
        }
    }

    public boolean needGroupintercomVideoEncoder() {
        if (this.handler != null) {
            return this.handler.needGroupintercomVideoEncoder();
        }
        return false;
    }

    public IGSPlatformConsumer createGroupintercomConsumer(IGSVideoEncoder iGSVideoEncoder) {
        if (this.handler != null) {
            return this.handler.createGroupintercomConsumer(iGSVideoEncoder);
        }
        return null;
    }

    public void onKeyAction(int i) {
        if (this.handler != null) {
            this.handler.onKeyAction(i);
        }
    }

    public void switchAudioRecordMode(int i) {
        if (this.handler != null) {
            this.handler.switchAudioRecordMode(i);
        }
    }

    public boolean isRunning() {
        if (this.handler != null) {
            return this.handler.isRunning();
        }
        return false;
    }

    public void startBusy() {
        if (this.handler != null) {
            this.handler.startBusy();
        }
    }

    public void stopBusy() {
        if (this.handler != null) {
            this.handler.stopBusy();
        }
    }

    public Single<Boolean> startBind(Context context, String str, String str2, String str3, String str4) {
        if (this.handler != null) {
            return this.handler.startBind(context, str, str2, str3, str4);
        }
        return Single.just(Boolean.FALSE);
    }

    public Single<Boolean> startFaceBind(String str) {
        if (this.handler != null) {
            return this.handler.startFaceBind(str);
        }
        return Single.error(new Exception("platfom no support"));
    }

    public void inputAudioData(byte[] bArr) {
        if (this.handler != null) {
            this.handler.inputAudioData(bArr);
        }
    }

    public String getPlatformDeviceId() {
        return this.handler != null ? this.handler.getPlatformDeviceId() : EnvironmentCompat.MEDIA_UNKNOWN;
    }


    public Single<Boolean> setPlatformJsonSetting(String str) {
        if (this.handler != null) {
            return this.handler.setPlatformJsonSetting(str);
        }
        return Single.error(new Throwable("no support"));
    }

    public Single<Boolean> setPlatformJsonConfig(JsonObject jsonObject) {
        if (this.handler != null) {
            return this.handler.setPlatformJsonConfig(jsonObject);
        }
        return Single.error(new Throwable("no support"));
    }

    public void postAlarmTypeToPlatform(String str, String str2) {
        if (this.handler != null) {
            this.handler.postAlarmTypeToPlatform(str, str2);
        }
    }

    public void reportAction(String str, String str2) {
        if (this.handler != null) {
            this.handler.reportAction(str, str2);
        }
    }
}
